<template>
  <div>
    <div class="search">
      <input class="search-input" type="text" placeholder="输入城市名/拼音" v-model="keyword"/>
    </div>

    <div ref="wrapper" v-show="keyword">
      <div class="search-content">
        <div class="search-item" v-for="item of list" @click="handleClick(item.name)">{{item.name}}</div>
        <div class="search-item" v-show="hasNoData">没有找到数据</div>
      </div>

    </div>

  </div>

</template>

<script>
  import BScroll from 'better-scroll'
  import {mapMutations} from 'vuex'

  export default {
    name: 'CitySearch',
    props: {
      cities: Object
    },
    data: function () {
      return {
        keyword: '',
        timer: null,
        list: []
      }
    },
    methods: {
      handleClick: function (name) {
        // this.$store.dispatch('changeCity',name)
        // this.$store.commit('changeCity', name)
        this.changeCity(name)
        this.$router.push('/')
      },
      ...mapMutations(['changeCity'])

    },
    watch: {
      /**
       * 一旦搜索内容改变的话
       */
      keyword: function () {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        if (!this.keyword) {
          this.list = []
          return
        }
        this.timer = setTimeout(() => {
          const results = []
          for (let i in this.cities) {
            this.cities[i].forEach((value) => {
              /**
               *如果拼音或者汉字相似就添加进去
               */
              if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
                results.push(value)
              }
            })
          }
          this.list = results
        }, 100)
      }
    },
    mounted: function () {
      this.scroll = new BScroll(this.$refs.wrapper)
    },
    computed: {
      hasNoData: function () {
        return !this.list.length
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .search {
    height .72rem;
    background $bgColor
    padding 0 .1rem
  }

  .search-input {
    box-sizing border-box
    height .62rem
    line-height .62rem
    width 100%
    text-align center;
    border-radius .06rem
    color #666
    padding 0 .1rem
  }

  .search-content {
    z-index 1
    overflow hidden
    position absolute
    top: 1.58rem
    left 0
    right 0
    bottom: 0
    background #eee
  }

  .search-item {
    line-height .62rem
    padding-left .2rem
    color #666
    background white
    border-bottom 1px solid #dbdbdb
  }
</style>
